package com.ophiux.filter;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.MessageSelector;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * @desc: 过滤消息消费者 -tag方式
 * @author: hhl
 * @date：2023/8/17 15:35
 * 遇到报错时：CODE: 1  DESC: The broker does not support consumer to filter message by SQL92
 * 在borker.conf中添加：
        #支持sql92
        enablePropertyFilter=true
 */
public class FilterSqlConsumer {

    public static void main(String[] args) throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("FilterSqlConsumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        consumer.subscribe("FilterSql", MessageSelector.bySql("TAGS is not null and TAGS in ('TagA','TagB') " +
                "and (name is not null and name<5)"));
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                list.forEach(item -> {
                    System.out.println(item.getTags() + "消息消费成功：" + new String(item.getBody()));
                });
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();
    }
}
